package com.platform.common.entity;


import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description 用于构建树状结构的工具类
 * @author ganyimeng
 */
@Data
public class TreeNode implements Serializable{
	
	private static final long serialVersionUID = 1L;

	@JsonIgnore
	public static Map<String,String> permiss = new HashMap<>();
	
	
	//@JsonIgnore
	private String id;
	//@JsonIgnore
	private String name;
	//@JsonIgnore
	private String parentId;
	
	@JsonIgnore
	private String code;
	
	@JsonIgnore
	@TableField(exist = false)
	private Boolean permission;
	
	@TableField(exist = false)
	private List<TreeNode> children = new ArrayList<>();
	
	
	public static List<TreeNode> buildTreeNodes(List<TreeNode> list){
		List<TreeNode> trees = new ArrayList<>();
		
		Map<String, TreeNode> map = list.stream().collect(
				Collectors.toMap(e->{
	                return e.getId();
	            },e->{
	                return e;
	            })
			);
		
		for(TreeNode v : list) {	
			String parentId = v.getParentId();
			if(parentId!=null) {
				TreeNode node = map.get(parentId);
				if(node == null) {
					trees.add(v);
				}else {
					node.getChildren().add(v);
				}
			}else {
				trees.add(v);
			}
		}
		return trees;
	}
}
